var Storgae_Status_Normal = 0;


layui.config({});
layui.use(['form', 'admin', 'ax', 'jquery', 'steps', 'laydate', 'formSelects'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var laydate = layui.laydate;
    var formSelects = layui.formSelects;

    //data
    var materialList = [];
    var productList = [];


    //select
    var selectMaterials = [];
    var selectProducts = [];
    var selectWorker;
    var selectPood;
    var storageStatus = 0;
    var storageStatusDesc = '入库';

    //load
    var resultData;



    //获取详情信息，填充表单
    if (!Feng.isUndefined(Feng.getUrlParam("storageId"))){
        var ajax = new $ax(Feng.ctxPath + "/api/storage/detail?storageId=" + Feng.getUrlParam("storageId"));
        var result = ajax.start();
        resultData = result.data;
        form.val('storageForm', resultData);

        selectWorker = resultData.worker;
        selectPood = resultData.poodId;
        storageStatus = resultData.status+"";
        if (!Feng.isUndefined(resultData.materielList)) {
            selectMaterials = JSON.parse(resultData.materielList);
        }
        if (!Feng.isUndefined(resultData.productList)) {
            selectProducts = JSON.parse(resultData.productList);
        }
        $("#body_form").addClass("layui-not-events");
        $("#saveButton").addClass("layui-not-events");
        $("#saveButton").html("编辑只能查看");

    }


    //初始化数据

    loadResultData();

    //加载信息
    function loadResultData() {

        loadUI();


        //加载物料
        loadMaterialList();

        //加载产品
        loadProductList();

        // 人员
        loadWorkerList();

        // 养殖池
        loadPoodList();


    }

    /**
     * 状态
     */
    function loadUI() {

        var productForm = $("#productForm");

        if (Feng.isUndefined(Feng.getUrlParam("storageId"))){
            storageStatus = Feng.getUrlParam("storageStatus");
        }
        if (storageStatus === "0") {
            storageStatusDesc = '入库';
        }else if (storageStatus === "1") {
            storageStatusDesc = '出库';
            productForm.addClass("hide");
        }else if (storageStatus === "2") {
            storageStatusDesc = '移库';
            productForm.addClass("hide");
        }
        $("#statusDesc").html(storageStatusDesc);

    }

    //加载物料
    function loadMaterialList() {

        $("#materielSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/api/materiel/list", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].title;
                var value = data.data[i].materielId;
                var specs = data.data[i].specs;
                var number = data.data[i].number;
                var unit = data.data[i].unit;
                var dict = {"value": value, "name": name, "specs": specs, "maxNumber": number, "unit": unit};
                materialList.push(dict);
            }
            mutilMateriels();
            form.render();

        }, function (data) {
        });
        ajax.start();
    }

    function mutilMateriels() {
        if (Feng.isArray(materialList)) {
            formSelects.data('materielSelect', 'local', {
                arr: materialList
            });

            if (Feng.isArray(selectMaterials)) {
                var materialIds = [];
                for (var i = 0; i < selectMaterials.length; i++) {
                    var select = selectMaterials[i];
                    materialIds.push(select.value);
                }
                formSelects.value('materielSelect', materialIds);
                loadMaterielsItemList();
            }
        }

    }

    formSelects.on('materielSelect', function (id, vals, val, isAdd, isDisabled) {
        // alert("选择了: " + val.name);
        selectMaterials = vals;
        loadMaterielsItemList();

    }, true);


    function loadMaterielsItemList() {

        var materielsItemList = $("#materielsItemList");
        materielsItemList.html('');
        for (var i = 0; i < selectMaterials.length; i++) {

            var material = selectMaterials[i];
            var name = selectMaterials[i].name;
            var specs = selectMaterials[i].specs;
            var maxNumber = selectMaterials[i].maxNumber;
            var number = selectMaterials[i].number;
            var numberName = 'materiel_number_' + i;

            var itemForm = '<div class="layui-col-md12">';
            var nameForm = '<div class="layui-inline layui-col-md4">' +
                '<label class="layui-form-label">物料</label>' +
                '<div class="layui-input-block" style="line-height: 38px">' +
                name +
                '</div>' +
                '</div>';

            var weightForm = '<div class="layui-inline layui-col-md4">' +
                '<label class="layui-form-label">重量(g)</label>' +
                '<div class="layui-input-block" style="line-height: 38px">' +
                specs +
                '</div>' +
                '</div>';

            var numberTip = "数量(斤)" + "(<=" + maxNumber + ")";
            if (!Feng.isUndefined(resultData)) {
                numberTip = "数量(斤)";
            }
            var numberForm = '<div class="layui-inline layui-col-md4">' +
                '<label class="layui-form-label">' + numberTip + '</label>' +
                '<div class="layui-input-block">' +
                '<input   id= ' + numberName + ' name=' + numberName + ' value= ' + number + '  type="number"  class="layui-input" />' +
                '</div>' +
                '</div>';

            itemForm += nameForm;
            itemForm += weightForm;
            itemForm += numberForm;
            itemForm += '</div>';
            materielsItemList.append(itemForm);

        }

    }
    //加载目标产品

    function loadProductList() {

        $("#productSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/api/product/list", function (data) {

            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].title;
                var value = data.data[i].productId;
                // var weight = data.data[i].weight;
                var dict = {"value": value, "name": name, "weight": "0", "number": "0"};
                productList.push(dict);
            }
            mutilProducts();
            form.render();

        }, function (data) {
        });
        ajax.start();
    }


    function mutilProducts() {
        if (Feng.isArray(productList)) {

            formSelects.data('productSelect', 'local', {
                arr: productList
            });
            if (Feng.isArray(selectProducts)) {
                var productIds = [];
                for (var i = 0; i < selectProducts.length; i++) {
                    var select = selectProducts[i];
                    productIds.push(select.value);
                }
                formSelects.value('productSelect', productIds);
                loadProductItemList();
            }
        }

    }

    formSelects.on('productSelect', function (id, vals, val, isAdd, isDisabled) {
        // alert("选择了: " + val.name);
        selectProducts = vals;
        loadProductItemList();

    }, true);

    // formSelects.on('productSelect', function (obj) {
    //
    //     selectProducts = obj.checkedData;
    // });

    function loadProductItemList() {
        $("#productItemList").html('');
        for (var i = 0; i < selectProducts.length; i++) {
            var name = selectProducts[i].name;
            var weight = selectProducts[i].weight;
            var number = selectProducts[i].number;
            var numberName = 'product_number_' + i;

            var itemForm = '<div class="layui-col-md12">';
            var nameForm = '<div class="layui-inline layui-col-md3">' +
                '<label class="layui-form-label">产品</label>' +
                '<div class="layui-input-block" style="line-height: 38px">' +
                name +
                '</div>' +
                '</div>';

            var numberForm = '<div class="layui-inline layui-col-md3"><label class="layui-form-label">数量(斤)</label>' +
                '<div class="layui-input-block">' +
                '<input id= ' + numberName + ' name=' + numberName + ' value=' + number + '  type="number"  class="layui-input"/>' +
                '</div>' +
                '</div>';

            itemForm += nameForm;
            itemForm += numberForm;
            itemForm += '</div>';
            $("#productItemList").append(itemForm);


        }

    }

     /**
     * 加载工作人员
     */
    function loadWorkerList() {

        $("#workerSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/mgr/allList", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].name;
                var account = data.data[i].account;
                var value = account + "-" + name;
                var select = '';
                if (value === selectWorker) {
                    select = 'selected';
                }
                if (i === 0 && Feng.isUndefined(selectWorker) && value!==selectWorker) {
                    selectWorker = value;
                    select = 'selected';
                }
                var selected = select;
                $("#workerSelect").append('<option value="' + value + '"  '+selected+'>' + value + '</option>');
            }
            form.render();

        }, function (data) {
        });
        ajax.start();
    }
    form.on('select(workerSelect)', function (data) {
        selectWorker = data.value;
    });
    /**
     * 加载养殖池
     */
    function loadPoodList() {

        $("#poodSelect").html('');
        var ajax = new $ax(Feng.ctxPath + "/api/pood/list?limit=100", function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var name = data.data[i].title;
                var value = data.data[i].poodId;
                var select = '';
                if (name === selectPood) {
                    select = 'select';
                }
                if (i===0 && selectPood === undefined) {
                    selectPood = value;
                }
                var optionValue = value + select;
                $("#poodSelect").append('<option value="' + optionValue + '">' + name + '</option>');
            }
            form.render();

        }, function (data) {
        });
        ajax.start();
    }
    form.on('select(poodSelect)', function (data) {
        selectPood = data.value;
    });






    //让当前iframe弹层高度适应
    admin.iframeAuto();


    //请求体

    function parseMaterialList() {
        for (var i = 0; i < selectMaterials.length; i++) {
            var materiel = selectMaterials[i];
            var numberClass = "materiel_number_" + i;
            var number = $("#" + numberClass).val();
            if (!Feng.isUndefined(number)) {
                materiel.number = number;
            }
            selectMaterials[i] = materiel;

        }
    }

    function parseProductList() {
        for (var i = 0; i < selectProducts.length; i++) {
            var product = selectProducts[i];
            var numberClass = "product_number_" + i;
            var number = $("#" + numberClass).val();
            if (!Feng.isUndefined(number)) {
                product.number = number;
            }

            selectProducts[i] = product;

        }
    }


    function buildRequest() {

        parseMaterialList();
        parseProductList();

        if (Feng.isUndefined(selectPood) === true) {
            Feng.error("养殖池不能为空");
            return false;
        }

        if (Feng.isUndefined(selectWorker) === true) {
            Feng.error("执行人不能为空");
            return false;
        }

        if (storageStatus === "0") {
            if (Feng.isArray(selectMaterials) === false && Feng.isArray(selectProducts) === false) {
                Feng.error("原料/产品不能都为空");
                return false;
            }
        }else  {
            if (Feng.isArray(selectMaterials) === false) {
                Feng.error("原料不能为空");
                return false;
            }
        }


        return true;
    }

    //表单提交事件
    var url = "/api/storage/addItem";
    if (!Feng.isUndefined(Feng.getUrlParam("storageId"))){
        url = "/api/storage/editItem";
    }
    form.on('submit(btnSubmit)', function (data) {

        var result = buildRequest();
        if (result === false) {
            return;
        }


        data.field.poodId = selectPood;
        data.field.worker = selectWorker;
        data.field.status = parseInt(storageStatus);
        data.field.statusDesc = storageStatusDesc;


        //原料
        if (Feng.isArray(selectMaterials)) {
            data.field.materielList = JSON.stringify(selectMaterials);
        }
        if (Feng.isArray(selectProducts)) {
            data.field.productList = JSON.stringify(selectProducts);
        }

        var ajax = new $ax(Feng.ctxPath + url, function (data) {
            Feng.success("操作成功！");
            window.location.href = Feng.ctxPath + '/api/storage'
        }, function (data) {
            Feng.error("操作失败！" + data.responseJSON.message)
        });
        ajax.set(data.field);
        ajax.start();

        return false;
    });


    // 添加按钮点击事件
    $('#btnExp').click(function () {
        addMaterielItemList();
    });

    //返回按钮
    $("#backupPage").click(function () {
        window.location.href = Feng.ctxPath + '/api/storage'
    });


});